<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'timOfEntry', order: 'ascending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!--  sorble 排序  排列顺序 方法 -->
          <el-table-column sorble label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formEmployeesEnum(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <EmpDialog ref="resetFormRef" @close="showDialog = false" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// 方法 其一
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
import { getemployees, delEmployee } from '@/api/employees'
// 取出枚举中的数据
import EmployeesEnum from '@/constant/employees'
import EmpDialog from './empDialog.vue'

// 方法 其二  reduce
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log('hireType', hireType)
export default {
  name: 'Employees',
  components: {
    EmpDialog
  },
  data() {
    return {
      showDialog: false,
      // 页码值,默认第一页
      page: 1,
      // 每页显示的条数
      size: 5,
      // 保存员工数据
      list: [],
      total: 0
    }
  },
  created() {
    this.loademployees()
  },
  methods: {
    formatDate(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      // 如果list中有数组,才需要生成表头
      if (!one) return
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      // 2. 生成data数据
      const data = list.map(item => {
        const key = item.formOfEmployment
        // hireType = {1:'正式',2:'非正式'}
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      return { header: header, data: data }
    },

    // 导出功能的关键代码
    async handleDownload() {
      try {
        const res = await getemployees(this.page, this.size)
        // 从后台获取到的数据

        // console.log(res.data.rows)
        //  import('@/vendor/Export2Excel') 懒加载的方式导入一个模块(文件)
        const { header, data } = this.formatDate(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          // excel 指的是模块对象 , 可以使用excel 调用@/vendor/Export2Excel这个文件中的文件属性
          // excel.export_json_to_excel

          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存数据
      } catch (err) {
        console.log('getemployees', err)
      }
    },
    // 1. 删除员工信息
    hDel(id) {
      this.$confirm('您确认要删除吗?').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        // 3.优化删除功能
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 2. 删除之后重新加载页面
        this.loademployees()
      }).catch((error) => {
        console.log(error)
      })
    },
    // 重置表单
    hResetForm() {
      this.$refs.resetFormRef.resetForm()
    },
    hSuccess() {
      // 优化 : 计算出最大的页码值
      this.total++
      const mapPage = Math.ceil(this.total / this.size)
      this.page = mapPage
      // 重新渲染
      this.loademployees()
      // 关闭弹层
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loademployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loademployees()
    },
    formEmployeesEnum(data) {
      // console.log('hireType[data]', hireType[data])
      return hireType[data] || '未知'

      // 保存数据
    },

    async loademployees() {
      try {
        const res = await getemployees(this.page, this.size)
        console.log('getemployees', res)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('getemployees', err)
      }
    }
  }
}
</script>
